//
//  HOTCreateArticleViewController.m
//  Genpara
//
//  Created by zhang chunhui on 14-9-30.
//  Copyright (c) 2014年 zhangchh. All rights reserved.
//

#import "HOTCreateArticleViewController.h"
#import "ZZZUIScrollView+Extends.h"
#import "UITextField+extend.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "AFHTTPRequestOperationManager.h"

@interface HOTCreateArticleViewController () <UITextFieldDelegate, UITextViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
    
    AFHTTPRequestOperationManager *manager;
}
@property(nonatomic,copy)NSString *category_id;
@property(nonatomic,strong)NSString *uploadImagePath;
@end

@implementation HOTCreateArticleViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil category_id:(NSString *)category_id
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.category_id = category_id;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_oreno"]];
    [self setNaviTitle:@"新規投稿"];
    
    bgImageView.image = [bgImageView.image resizableImageWithCapInsets:UIEdgeInsetsMake(20, 20, 20, 20)];
    
    [self addRightBtnTarget:self action:@selector(saveBtnClicked) image:[UIImage imageNamed:@"btn_contribute_off"] hImage:[UIImage imageNamed:@"btn_contribute_on"]];
    
    _contentTextView.inputAccessoryView = [HOTUtils createInputAccessoryViewWithName:MSG_INPUT_BAR_DONE target:self action:@selector(doneBtnClicked)];
}

-(void)saveDataToNet {
    
    [self showLoading];
    
    __unsafe_unretained HOTCreateArticleViewController *unsafeObj = self;
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_USER_ID:self.userInfo.userId,
                                 REQ_KEY_CATE_ID:self.category_id,
                                 REQ_KEY_REPLAY_CONTENT:[HOTUtils getString:_contentTextView.text],
                                 REQ_KEY_REPLAY_TITLE:[HOTUtils getString:_titleTextField.text],
                                 REQ_KEY_PIC_UPLOAD:[HOTUtils getString:self.uploadImagePath]
                                 };
    
    //__unsafe_unretained HOTCloseDownDetailListViewController *tempObj = self;
    [self requestWithURL:HOT_URL_MY_SERIES_INFO Parameters:parameters success:^(NSInteger result, NSDictionary * dataArr) {
        
        [self showSuccessWithMessage:MSG_SUCCESS complection:^{
            
            [unsafeObj.navigationController popViewControllerAnimated:YES];
        }];
        
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [unsafeObj loadingSuccess];
        
        if ([unsafeObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}

-(void)saveBtnClicked {
    
    [_titleTextField resignFirstResponder];
    [_contentTextView resignFirstResponder];
    [_mainScrollView setContentOffset:CGPointMake(0, 0)];
    
    if (![self checkParameters]) {
        
        return;
    }
    
    [self saveDataToNet];
}

-(BOOL)checkParameters {
    
    if ([_titleTextField textIsNullOrEmpty]) {
        
        NSString *errMsg = [self getErrMsgWith:@"タイトル" itemType:HOTInputItemText];
        
        ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                              message:errMsg
                                                             delegate:nil
                                                    cancelButtonTitle:nil
                                                     otherButtonTitle:ALERT_BTN_OK];
        
        [popupView showInWindow];
        return NO;
    } else if ([HOTUtils isNullOrEmpty:_contentTextView.text]) {
        
        NSString *errMsg = [self getErrMsgWith:@"内容" itemType:HOTInputItemText];
        
        ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                              message:errMsg
                                                             delegate:nil
                                                    cancelButtonTitle:nil
                                                     otherButtonTitle:ALERT_BTN_OK];
        
        [popupView showInWindow];
        return NO;
    }
    
    return YES;
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    [_mainScrollView scrollViewToVisible:textField animated:YES];
    
    return YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    
    [_mainScrollView setContentOffset:CGPointMake(0, 0)];
    
    return YES;
}

-(BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    
    //[_mainScrollView scrollViewToVisible:textView animated:YES];
    [_mainScrollView scrollViewToVisible:textView
                      offsetY:40
                     animated:YES];
    return YES;
}

-(void)doneBtnClicked {
    
    [_contentTextView resignFirstResponder];
    [_mainScrollView setContentOffset:CGPointMake(0, 0)];
}

#pragma mark - UIImagePickerController delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    //获取照片的原图
    UIImage *selImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    NSData *imageData = UIImageJPEGRepresentation(selImage,0.5);;
    
    [self showLoading];
    
    __unsafe_unretained HOTCreateArticleViewController *tempObj = self;
    [self uploadImageWithPost:HOT_URL_UPLOAD imageData:imageData uploadName:@"file_path" Parameters:nil success:^(NSDictionary * data) {
        
        [tempObj showSuccessWithMessage:MSG_UPLOAD_SUCCESS];
        
        tempObj.uploadImagePath = [data objectForKey:@"url"];
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)uploadBtnClicked:(id)sender {
    
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    
    ipc.delegate = self;
    [self presentViewController:ipc animated:YES completion:nil];
}
@end
